package com.kun.admin.authority.service;

import com.github.pagehelper.Page;
import com.kun.admin.authority.dao.AuthorityUserDao;
import com.kun.admin.authority.model.RoleModel;
import com.kun.admin.authority.model.UserVo;
import com.kun.base.config.Config;
import com.kun.base.fs.FileSystem;
import com.kun.base.fs.FileSystemFactory;
import com.kun.base.model.UserAndInfoModel;
import com.kun.util.FileUtil;
import com.kun.util.MD5;
import com.kun.util.StringUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/9/20 0020.
 */
@Service
public class AuthorityUserServiceImpl implements AuthorityUserService {

    private static Logger logger = LoggerFactory.getLogger(AuthorityUserServiceImpl.class);

    @Autowired
    private AuthorityUserDao userDao;

    private FileSystem fileSystem = FileSystemFactory.getFileSystem();

    @Override
    public Page<UserAndInfoModel> list() {
        return userDao.list();
    }

    /**
     * 根据用户id获取用户
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public UserAndInfoModel getUserById(Long userId) {
        return userDao.queryUserById(userId);
    }

    /**
     * 更新用户的基本数据
     *
     * @param userAndInfoModel
     * @return
     */
    @Override
    public int updateBaseUserInfo(UserAndInfoModel userAndInfoModel) {
        UserAndInfoModel user = userDao.queryUserById(userAndInfoModel.getId());
        if (!user.getUsername().equals(userAndInfoModel.getUsername())){
            if (userDao.hasName(userAndInfoModel.getUsername()).size()>0){
                return -1;
            }
        }
        return userDao.updateBaseInfo(userAndInfoModel);
    }

    /**
     * 将文件上传到服务器
     *
     * @param userId
     * @param file
     * @return
     */
    @Override
    public boolean uploadHeadImage(Long userId, MultipartFile file) {
        if (file == null) {
            logger.error("头像上传文件出错！！！");
            return false;
        }
        String headImagePath = Config.HEAD_IMAGE_PATH;
        String fileName = "/" + StringUtil.getTimeString() + "/" + System.currentTimeMillis() + (int) (Math.random() * 100) + file.getOriginalFilename();
        String filePath = headImagePath + fileName;
        try {
            //文件保存到服务器
            fileSystem.mkdirs(FileUtil.getParentFilePath(filePath));
            if (fileSystem.write(filePath, file.getInputStream()) > 0) {
                //删除以前的头像文件
                String oldPath = userDao.queryHeadPath(userId);
                if (!StringUtil.isEmpty(oldPath)) {
                    fileSystem.delete(headImagePath + oldPath);
                }
                //把文件名保存到数据库
                userDao.updateHeadImagePath(userId, fileName);
                return true;
            } else {
                logger.error("头像文件保存失败：userId->" + userId + ";路径：" + filePath);
            }
        } catch (IOException e) {
            logger.error("获取上传的文件流失败", e);
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 修改用户密码
     *
     * @param userId      用户id
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 修改结果信息
     */
    @Override
    public String updatePwd(Long userId, String oldPassword, String newPassword) {
        UserAndInfoModel userAndInfoModel = userDao.queryUserById(userId);
        if (userAndInfoModel.getPassword().equals(MD5.GetMD5Code(oldPassword))) {
            int i = userDao.updatePwd(userId, MD5.GetMD5Code(newPassword));
            if (i == 0) {
                logger.error("用户userId:" + userId + "密码修改失败;数据库更新返回受影响的行数为0");
                return "密码修改失败";
            } else {
                return "密码修改成功";
            }
        } else {
            logger.error("用户userId:" + userId + "密码修改失败;用户输入密码错误");
            return "密码错误！！！";
        }
    }

    /**
     * 添加用户,只插入用户名和密码
     *
     * @param addUserName
     * @param addUserPassword1
     * @return
     */
    @SuppressWarnings("AlibabaTransactionMustHaveRollback")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addUser(String addUserName, String addUserPassword1) {
        String msg = "添加用户失败";
        UserAndInfoModel userAndInfoModel = new UserAndInfoModel();
        List<String> usernames = userDao.hasName(addUserName);
        if (usernames != null && usernames.size() > 0) {
            return "该用户名已存在";
        }
        userDao.addUserInfo(userAndInfoModel);
        if (userAndInfoModel.getInfoId() > 0) {
            userAndInfoModel.setUsername(addUserName);
            userAndInfoModel.setPassword(MD5.GetMD5Code(addUserPassword1));
            userDao.insertUser(userAndInfoModel);
            if (userAndInfoModel.getId() > 0) {
                return "添加用户成功";
            }
        }
        return msg;
    }

    /**
     * 获取用户的所有角色
     *
     * @param userId
     * @return
     */
    @Override
    public ArrayList<RoleModel> findUserRole(Long userId) {
        return userDao.findUserRole(userId);
    }

    /**
     * 为用户添加角色
     *
     * @param userId
     * @param roleId
     * @return
     */
    @Override
    public boolean addRole(Long userId, Long roleId) {
        int i = userDao.addRole(userId, roleId);
        return i>0;
    }

    /**
     * 移除用户角色
     *
     * @param userId
     * @param roleId
     * @return
     */
    @Override
    public boolean deleteRole(Long userId, Long roleId) {
        int i = userDao.deleteRole(userId, roleId);
        return i>0;
    }

    @Override
    public Page<UserAndInfoModel> findUserList(UserVo userVo) {
        return userDao.findUserList(userVo);
    }

    @Override
    public List<Long> findUserDept(Long userId) {
        return userDao.findUserDept(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserDept(Long userId, long[] deptIds) {
        userDao.deleteUderDept(userId);
        if (deptIds!=null && deptIds.length>0){
            for (Long deptId : deptIds) {
                userDao.addUserDept(userId,deptId);
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addUserInfo(UserAndInfoModel userInfo) {
        if (StrUtil.isBlank(userInfo.getUsername())){
            return "用户名不能是空白";
        }
        List<String> usernames = userDao.hasName(userInfo.getUsername());
        if (usernames != null && usernames.size() > 0) {
            return "该用户名已存在";
        }
        userDao.addUserInfo(userInfo);
        userInfo.setPassword(MD5.GetMD5Code(Config.INIT_PASSWORD));
        userDao.insertUser(userInfo);
        return "添加成功";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(Long userId) {
        UserAndInfoModel user = userDao.queryUserById(userId);
        if (user!=null){
            userDao.deleteUser(userId);
            if (user.getInfoId()>0){
                userDao.deleteUserInfo(user.getInfoId());
            }
            return true;
        }
        return false;
    }

    @Override
    public String findHeadImagePath(Long userId) {
        List<String> pathList=userDao.findHeadImagePath(userId);
        if (pathList.size()>0){
            return pathList.get(0);
        }
        return null;
    }
}
